<?php
declare (strict_types=1);

namespace app\service;

use MongoDB\Driver\Query;
use think\App;
use app\model\FetchUrlModel;
use app\service\TaskService;


class FetchManagerService extends \think\Service
{
    private $fetchUrlModel;

    public function __construct(App $app, FetchUrlModel $fetchUrlModel, TaskService $taskService, StorageService $storageService)
    {
        $this->app = $app;
        $this->fetchUrlModel = $fetchUrlModel;
        $this->taskService = $taskService;
        $this->storageService = $storageService;
    }

    function save($fetch_log_id, $remote_total, $list)
    {
        $this->storageService->handle($fetch_log_id, $remote_total, $list);
    }

    /**
     * 获取最后一个数据URL集合,用最新数据生成数据结构
     * @return array 最后一个数据URL集合
     */
    function getLastDataUrlSet($fetch_url_id=0)
    {
        $list = $this->fetchUrlModel->when([
                $fetch_url_id => function (Query $qeury) use ($fetch_url_id) {
                        $qeury->where('fetch_url_id', $fetch_url_id);
                }
            ]
        )->select();
        $rt = [];
        foreach ($list as $key => $row) {
            $tableName = $row['table_name'];
            $rt[$tableName] = TaskService::getUrl($tableName, $row['url'], 'desc', 0, 1);
        }
        return $rt;
    }


    /**
     * 设置远程总数,总数用于生成任务
     * @param $table_name
     * @param $total
     * @return FetchUrlModel
     */
    function setRemoteTotal($table_name, $total)
    {
        return $this->fetchUrlModel->where('table_name', $table_name)->update(['remote_total' => $total]);
    }

    /**
     * 创建任务
     * 考虑已经采集数据
     * 考虑远端删除修复
     */
    function createTask($fetch_url_id = 0)
    {
        $rt = [];
        $list = $this->fetchUrlModel
            ->where('state',FetchUrlModel::STATUS_FETCHING)
            ->order('remote_total', 'asc')->select()->column(null, 'id');

        if (isset($list[$fetch_url_id]) && $row = $list[$fetch_url_id]) {
            $rt = $this->taskService->createTask($row['id'], $row['remote_total'], $row['table_name']);
        }
        // 指定表优先
        if (!$rt) {
            foreach ($list as $key => $row) {
                $rt = $this->taskService->createTask($row['id'], $row['remote_total'], $row['table_name']);
                if ($rt) {
                    break;
                }
            }
        }
        return $rt;
    }

    /**
     * 提取任务
     * @return array|mixed
     */
    function takeTask($fetch_url_id = 0)
    {
        $rt = [];
        $task = $this->taskService->findFailedTask();
        if (!$task) {
            $task = $this->createTask($fetch_url_id);
        }
        if (isset($task['id'])) {
            $rt = $this->taskService->start($task['id']);
        }
        return $rt;
    }
}
